package com.tgy;

import com.common.sort.tools.Times;

/**
 * @Author: tgy
 * @Date: 2020-10-13 10:40
 */
public abstract class Sort<E> {

    protected E[] elements;

    private int swapCount;

    private int cmpCount;

    private int moveCount;

    public Long time;

    public void sort(E[] elements){

        this.elements = elements;

        long begin = System.currentTimeMillis();
        sort();
        time = System.currentTimeMillis() - begin;
    }

    protected void sort() {

    }

    protected int compare(int i1,int i2) {

        return compare(elements[i1],elements[i2]);
    }

    protected int compare(E e1,E e2) {

        cmpCount++;
        return ((Comparable<E>)e1).compareTo(e2);
    }

    protected void swap(int i1, int i2) {

        if (i1 == i2) {
            return;
        }
        swapCount++;
        E tmp = elements[i1];
        addMoveCount();
        elements[i1] = elements[i2];
        addMoveCount();
        elements[i2] = tmp;
        addMoveCount();
    }

    protected void addMoveCount() {

        moveCount++;
    }

    public boolean stable() {

        if (this.getClass().equals(CountingSort.class)) {

            return true;
        }

        int size = 10;
        Person[] pers = new Person[size];

        for (int i = 0; i < size; i++) {

            pers[i] = new Person(10,i + 1);
        }


        try {
            Sort sort = this.getClass().newInstance();
            sort.sort(pers);
        } catch (Exception e) {
            e.printStackTrace();
        }

        for (int i = 1; i < size; i++) {

            if (pers[i  - 1].getScore() > pers[i].getScore()) {

                return false;
            }
        }

        return true;
    }

    @Override
    public String toString() {

        return this.getClass().getSimpleName() + "\t 消耗时间:" + time
                    + "ms\t 交换次数: "+ swapCount
                    + "\t 比较次数:" + cmpCount
                    + "\t 是否稳定: " + stable();
    }

    public void print() {

        System.out.format("%-20s\t消耗时间:%-10d\t交换次数:%-15d\t比较次数:%-15d\t移动次数:%-15d\t是否稳定:%-2s\n",this.getClass().getSimpleName(),time,swapCount,cmpCount,moveCount,stable()?"稳定":"不稳定");
    }
}
